//#region 

async function plugInHandle(tab){
  chrome.scripting.executeScript({
    target : {tabId : tab.id},
    func : (tabId)=>{
      if(typeof(window.__fullScreenFn) === 'object'){
        // console.log('capturing')
        window.__fullScreenFn.execute()
      }else{
        // console.log('not fullScreenFn')
        chrome.runtime.sendMessage({ msg: 'none' })
      }
    },
    args : [ tab.id ]
  })
}

chrome.action.onClicked.addListener(plugInHandle)

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse)=>{
  const { msg, num } = message
  const { tab } = sender
  if (msg === 'exit') {
    plugInHandle(tab)
  }else if(msg === 'none'){
    chrome.scripting.insertCSS({
      files: ["styles.css"],
      target: { tabId: tab.id }
    })
    chrome.scripting.executeScript({//使用await会影响：第一次点击，报错：Symbol.hasInstance:1 Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.
      target : {tabId : tab.id},
      files: ['scripts/client.js']
    })
    plugInHandle(tab)
  }else if(msg === true){
    chrome.action.setIcon({
      tabId: tab.id,
      path: 'images/icons/icon-24.png'
    })
  }else if(msg === false){
    chrome.action.setIcon({
      tabId: tab.id,
      path: 'images/icons/icon-24.2.png'
    })
  }
})

//#endregion

// // 动态请求访问特定网站的权限
// document.getElementById('request-permission').addEventListener('click', async () => {
//   try {
//     const granted = await chrome.permissions.request({
//       origins: ['https://example.com/*']
//     });
//     if (granted) {
//       console.log('权限已授予');
//     } else {
//       console.log('权限被拒绝');
//     }
//   } catch (error) {
//     console.error('权限请求错误:', error);
//   }
// });
